<template>
	<view class="uni-ad-admin--x flex">
		<view class="uni-ad-admin-card-header p-1015">
			数据明细
		</view>

		<uni-table ref="table" :loading="loading" emptyText="没有更多数据" border stripe type="" style="min-height: 600px;">
			<uni-tr>
				<block v-for="(mapper, index) in tableFieldsMap" :key="index">
					<uni-th v-if="mapper.title && !mapper.hidden" :key="index" align="center"
						:class="{'w100':index == 0}">
						<!-- #ifdef MP -->
						{{mapper.title}}
						<!-- #endif -->
						<!-- #ifndef MP -->
						<uni-tooltip v-if="mapper.tooltip">
							{{mapper.title}}
							<uni-icons type="help" color="#666" />
							<template v-slot:content>
								<view class="uni-ad-admin-tooltip-s">
									{{mapper.tooltip}}
								</view>
							</template>
						</uni-tooltip>
						<text v-else>{{mapper.title}}</text>
						<!-- #endif -->
					</uni-th>
				</block>
			</uni-tr>

			<block v-for="(item,index) in dataList">
				<uni-tr>
					<block v-for="(mapper, index) in tableFieldsMap" :key="index">
						<uni-td align="center" v-if="mapper.title && !mapper.hidden">
							{{item[mapper.field] ? item[mapper.field] : '0'}}
						</uni-td>
					</block>
				</uni-tr>
			</block>
		</uni-table>
		<view class="uni-pagination-box">
			<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
				:total="pagination.count" @change="onPageChanged" />
		</view>
	</view>
</template>

<script>
	import {
		fieldsMap,
		platformFieldsMap
	} from './fieldsMap.js'
	import timeUtil from '@/uni_modules/uni-ad-admin/js_sdk/timeUtil'
	import {
		adType,
		PositionTypeList
	} from '@/uni_modules/uni-ad-admin/js_sdk/adType'

	const db = uniCloud.database()
	const dbCmd = db.command
	export default {
		name: "uni-ad-detail-table",
		data() {
			return {
				loading: false,
				pagination: {
					size: 15,
					current: 1,
					count: 0
				},
				query: {
					appid: '',
					ad_region: 0,
					ad_platform: 0,
					start_time: 0,
					end_time: 0,
					search: {
						platformSelectValue: 1,
						adTypeSelectValue: 0,
						systemSelectValue: '',
						positionSelectValue: '',
						mpAdTypeSelectValue: 0
					}
				},
				tableFieldsMap: [],
				tableName: 'uni-ad-adp-revenues',
				dataList: [],
				toField: 2
			};
		},
		props: {
			unit: {
				type: String,
				default: '元'
			}
		},
		methods: {
			getHiddenColumn() {
				let fields = Object.assign({}, platformFieldsMap)

				if (this.query.ad_platform === 0) {
					fields = Object.assign({}, fieldsMap)
				}
				for (let i in fields) {
					delete fields[i].hidden
				}
				if (this.query.ad_platform === 1) {
					// sdk
					if (this.query.search.platformSelectValue !== 1) {
						// 隐藏名称，adp_id，系统类型
						let hiddenColumn = ['adp_name', 'adp_id', 'os']
						for (let i in fields) {
							if (hiddenColumn.indexOf(fields[i].field) !== -1) {
								fields[i].hidden = true
							}
						}
					}
				}

				return fields
			},
			start(params) {
				this.query = params
				this.pagination.current = 1
				if (this.query.ad_region === 2) {
					this.toField = 3
				}

				if (this.query.ad_platform === 0) {
					this.tableFieldsMap = this.getHiddenColumn()
					this.loadDataPage()
				} else {
					this.tableFieldsMap = this.getHiddenColumn()
					this.loadDataPlatform()
				}
			},
			onPageChanged(e) {
				this.pagination.current = e.current

				if (this.query.ad_platform === 0) {
					this.loadDataPage()
				} else {
					this.loadDataPlatform()
				}
			},
			getQueryWhere() {
				let startDate = timeUtil.timeFormat(this.query.start_time, 'yyyyMMdd')
				let endDate = timeUtil.timeFormat(this.query.end_time, 'yyyyMMdd')

				let where = {
					appid: this.query.appid,
					ad_region: this.query.ad_region,
					revenue_date: dbCmd.and(
						dbCmd.gte(startDate),
						dbCmd.lte(endDate)
					)
				}
				if (this.query.ad_platform == 1) {

					// 渠道sdk广告
					if (this.query.search.platformSelectValue == 1) {
						where.ad_platform = 2

					} else {
						where.ad_platform = 1
					}
					// 广告类型
					if (this.query.search.adTypeSelectValue > 0) {
						where.ad_type = this.query.search.adTypeSelectValue
					}
					if (this.query.search.systemSelectValue) {
						where.os = this.query.search.systemSelectValue
					}
					if (this.query.search.positionSelectValue) {
						where.adp_id = this.query.search.positionSelectValue
					}
					//console.log('query',this.query.search)

				}
				if (this.query.ad_platform == 2) {
					where.ad_platform = 3
				}
				if (this.query.ad_platform == 3) {
					where.ad_platform = 4

					if (this.query.search.mpAdTypeSelectValue) {
						where.ad_type = this.query.search.mpAdTypeSelectValue
					}
				}
				// console.log('where',where)
				return where
			},
			// 分页数据
			loadDataPage() {
				let where = this.getQueryWhere()
				delete where.ad_platform

				let skip = (this.pagination.current - 1) * this.pagination.size

				this.loading = true
				db.collection('uni-ad-app-revenues')
					.where(where)
					.skip(skip)
					.limit(this.pagination.size)
					.orderBy('revenue_date desc')
					.get({
						getCount: true
					}).then(res => {
						let {
							data,
							count
						} = res.result
						this.pagination.count = count

						let start = 0
						let end = 0
						if (data.length) {
							start = data[data.length - 1].revenue_date
							end = data[0].revenue_date

							if (this.query.ad_platform === 0) {
								this.loadDataAll(start, end)
							} else {
								this.loadDataPlatform(start, end)
							}
						} else {
							this.loading = false
							this.dataList = []
						}
					})
			},
			loadDataAll(start, end) {
				let where = this.getQueryWhere()
				where.revenue_date = dbCmd.and(
					dbCmd.gte(start),
					dbCmd.lte(end)
				)

				db.collection(this.tableName)
					.where(where)
					.groupBy('revenue_date,ad_type')
					.groupField('sum(show_count) as show_count,sum(click_count) as click_count,sum(revenue) as revenue')
					.orderBy('revenue_date desc')
					.get()
					.then(res => {
						let {
							data
						} = res.result

						let dataList = this.getDateList(start, end)
						for (let i in dataList) {
							let revenue_date = dataList[i].revenue_date

							dataList[i].revenue_date = timeUtil.dateFormat(revenue_date)
							dataList[i].dcloud_push_click = this.getAdResultVal(data, revenue_date, adType.dcloud_push,
								'click_count')
							dataList[i].dcloud_red_packet_click = this.getAdResultVal(data, revenue_date, adType
								.dcloud_red_packet, 'click_count')
							dataList[i].dcloud_splash_show = this.getAdResultVal(data, revenue_date, adType
								.dcloud_splash, 'show_count')
							dataList[i].dcloud_splash_click = this.getAdResultVal(data, revenue_date, adType
								.dcloud_splash, 'click_count')
							dataList[i].sdk_splash_show = this.getAdResultVal(data, revenue_date, adType.sdk_splash,
								'show_count')
							dataList[i].sdk_splash_click = this.getAdResultVal(data, revenue_date, adType.sdk_splash,
								'click_count')
							dataList[i].full_video_show = this.getAdResultVal(data, revenue_date, adType
								.sdk_full_video, 'show_count')
							dataList[i].full_video_click = this.getAdResultVal(data, revenue_date, adType
								.sdk_full_video, 'click_count')
							dataList[i].video_show = this.getAdResultVal(data, revenue_date, adType.sdk_video,
								'show_count')
							dataList[i].video_click = this.getAdResultVal(data, revenue_date, adType.sdk_video,
								'click_count')
							dataList[i].message_show = this.getAdResultVal(data, revenue_date, adType.sdk_message,
								'show_count')
							dataList[i].message_click = this.getAdResultVal(data, revenue_date, adType.sdk_message,
								'click_count')
							dataList[i].draw_show = this.getAdResultVal(data, revenue_date, adType.sdk_draw,
								'show_count')
							dataList[i].draw_click = this.getAdResultVal(data, revenue_date, adType.sdk_draw,
								'click_count')
							dataList[i].union_show = this.getAdResultVal(data, revenue_date, adType.sdk_union,
								'show_count')
							dataList[i].plug_show = this.getAdResultVal(data, revenue_date, adType.sdk_plug,
								'show_count')
							dataList[i].plug_click = this.getAdResultVal(data, revenue_date, adType.sdk_plug,
								'click_count')
							dataList[i].mp_video_show = this.getAdResultVal(data, revenue_date, adType.mp_video,
								'show_count')
							dataList[i].mp_video_click = this.getAdResultVal(data, revenue_date, adType.mp_video,
								'click_count')
							dataList[i].game_show = this.getAdResultVal(data, revenue_date, adType.sdk_game,
								'show_count')

							dataList[i].dcloud_revenue = this.getAdResultVal(data, revenue_date, [
								adType.dcloud_push,
								adType.dcloud_splash,
								adType.dcloud_red_packet,
								adType.dcloud_unimp
							], 'revenue')
							dataList[i].sdk_splash_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_splash,
								'revenue')
							dataList[i].full_video_revenue = this.getAdResultVal(data, revenue_date, adType
								.sdk_full_video,
								'revenue')
							dataList[i].video_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_video,
								'revenue')
							dataList[i].message_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_message,
								'revenue')
							dataList[i].draw_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_draw,
								'revenue')
							dataList[i].union_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_union,
								'revenue')
							dataList[i].plug_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_plug,
								'revenue')
							dataList[i].mp_video_revenue = this.getAdResultVal(data, revenue_date, adType.mp_video,
								'revenue')
							dataList[i].game_revenue = this.getAdResultVal(data, revenue_date, adType.sdk_game,
								'revenue')
							dataList[i].revenue = this.getAdResultVal(data, revenue_date, 0,
								'revenue')
						}

						this.dataList = dataList
						this.loading = false
					})
			},
			getOsVal(row) {
				if (this.query.ad_platform == 1) {
					if (row.os == 'android') {
						return 'Android'
					} else {
						return 'iOS'
					}
				} else if (this.query.ad_platform == 2) {
					return 'H5'
				} else if (this.query.ad_platform == 3) {
					return '小程序'
				}
			},
			getAdResultVal(data, revenue_date, ad_type, sum_column) {
				let res = data.filter((item) => {
					if (ad_type instanceof Array) {
						return ad_type.includes(item.ad_type) && item.revenue_date == revenue_date
					} else {
						return (item.ad_type == ad_type || ad_type == 0) && item.revenue_date == revenue_date
					}
				})
				if (res.length == 0) {
					if (sum_column == 'revenue') {
						return this.getDataValFormat(0, sum_column)
					}
					return 0
				}

				let val = res.reduce(function(acc, obj) {
					return acc + obj[sum_column]
				}, 0)

				if (sum_column == 'revenue') {
					return this.getDataValFormat(val / 1000, sum_column)
				}
				return val
			},
			getDataValFormat(val, column) {
				if (column == 'revenue') {
					return val.toFixed(this.toField) + this.unit
				} else {
					return val
				}
			},
			async loadDataPlatform(start, end) {
				let where = this.getQueryWhere()

				this.loading = true
				let skip = (this.pagination.current - 1) * this.pagination.size
				db.collection(this.tableName)
					.where(where)
					.groupBy('revenue_date,adp_id,ad_type,os')
					.groupField(
						'sum(show_count) as show_count,sum(click_count) as click_count,sum(revenue) as revenue')
					.orderBy('revenue_date desc')
					.skip(skip)
					.limit(this.pagination.size)
					.get({
						getCount: true
					})
					.then(async res => {
						let {
							data,
							count
						} = res.result
						this.pagination.count = count
						let adpNames = []
						for (let i in data) {
							let adp_id = data[i].adp_id
							let revenue = data[i].revenue / 1000
							let adp = adpNames.find(item => {
								return item.adp_id == adp_id
							})
							let adp_name = ''
							if (!adp) {
								adp_name = await this.getPositionName(adp_id)
								adpNames.push({
									adp_id,
									adp_name
								})
							} else {
								adp_name = adp.adp_name
							}

							data[i].revenue_date = timeUtil.dateFormat(data[i].revenue_date)
							data[i].adp_name = adp_name
							data[i].ad_type = this.getPositionTypeName(data[i].ad_type)
							data[i].revenue = this.getDataValFormat(revenue, 'revenue')
							data[i].click_rate = this.getClickRate(data[i].click_count, data[i].show_count)
							data[i].cpc = this.getCPC(revenue, data[i].click_count) + this.unit
							data[i].cpm = this.getCPM(revenue, data[i].show_count) + this.unit
							data[i].os = this.getOsVal(data[i])
						}

						this.dataList = data
						this.loading = false
					})
			},
			getClickRate(click, show) {
				if (click > 0) {
					return (click / show * 100).toFixed(2) + '%'
				}
				return '0%'
			},
			getCPC(money, click) {
				let cpc = 0
				if (click > 0) {
					cpc = money / click
				}
				return cpc.toFixed(this.toField)
			},
			getCPM(money, show) {
				let cpm = 0
				if (show > 0) {
					cpm = money / show * 1000
				}
				return cpm.toFixed(this.toField)
			},
			getDateList(start, end) {
				let startDate = timeUtil.toTime(start)
				let endDate = timeUtil.toTime(end)

				let result = []
				for (let i = endDate; i >= startDate; i -= 86400000) {
					result.push({
						revenue_date: timeUtil.timeFormat(i, 'yyyyMMdd')
					})
				}
				return result
			},
			async getPositionName(adp_id) {
				let adps = await db.collection('uni-ad-positions')
					.where({
						adp_id,
						ad_region: this.query.ad_region
					}).get()

				if (adps.result.data.length) {
					return adps.result.data[0].adp_name
				}
				return ''
			},
			getPositionTypeName(ad_type) {
				let position = PositionTypeList.find((item) => {
					return item.value == ad_type
				})
				if (!position) {
					return ''
				}

				return position.text
			}
		}
	}
</script>

<style lang="scss">
	.uni-pagination-box {
		width: 100%;
		padding: 15px;
	}

	.uni-ad-admin-tooltip-s {
		width: 160px;
		white-space: normal;
	}

	.w100 {
		width: 100px;
	}
</style>